package controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import po.User;
import service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	/**
	 * @author CoinBin
	 */

	@Autowired
	private UserService userService;

	@RequestMapping("/select/{page}")
	public String select(Model model, @PathVariable int page) {
		int pageNumber = userService.count();
		page--;
		if (page >= pageNumber) {
			page = 0;
		}
		page *= 5;
		List<User> list = userService.serviceSelectAllUser(page);
		ArrayList<Integer> pages = new ArrayList<>();
		for (int i = 1; i <= pageNumber; i++) {
			pages.add(i);
		}
		model.addAttribute("userList", list);
//		System.out.println("====================");
		User user = new User();
		model.addAttribute("user", user);
		model.addAttribute("pageNumber", pageNumber);
		model.addAttribute("pages", pages);
		return "userlist";
	}

	@RequestMapping("/selectEml")
	public String selectByEmail(@ModelAttribute User user, Model model) {
		List<User> list = userService.serviceSelectEml(user);
		if (list.size() == 0) {
			model.addAttribute("selectMsg", "查询不到该email");
			return "forward:/user/select/1";
		}
		model.addAttribute("userList", list);
		model.addAttribute("user", user);
		return "userlist";
	}

	@RequestMapping("/delete/{id}")
	public String delete(Model model, @PathVariable int id) {
		int success = userService.serviceDelUser(id);
		if (success == 0) {
			return "delError";
		}

		return "forward:/user/select/1";
	}
}
